'use client'
import React, { useState, useEffect } from 'react';
import {
  Card,
  CardHeader,
  CardBody,
  Spinner,
  Button,
  Image
} from "@nextui-org/react";
import { BiChevronRight, BiChevronDown, BiFolderOpen, BiHomeAlt, BiChevronLeft, BiRefresh } from "react-icons/bi";
import { getCollectionTree, CollectionTreeItem } from '@/app/service/collectionService';
import PubSub from "pubsub-js";
import { useRouter } from 'next/navigation';

interface DirectoryTreeProps {
  onSelectDirectory: (id: string | null) => void;
  currentDirectoryId: string | null;
  onToggleVisibility?: () => void;
}

export default function DirectoryTree({ onSelectDirectory, currentDirectoryId, onToggleVisibility }: DirectoryTreeProps) {
  const [collections, setCollections] = useState<CollectionTreeItem[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [expandedNodes, setExpandedNodes] = useState<Set<number>>(new Set());

  useEffect(() => {
    fetchCollectionTree();
  }, []);

  //文件夹
  // PubSub.unsubscribe("refreshFolder")
  PubSub.subscribe("refreshFolder", (_, data) => {
    console.log("收到刷新消息:", data);
    fetchCollectionTree()
  })

  const fetchCollectionTree = async () => {
    setLoading(true);
    try {
      const data = await getCollectionTree();
      setCollections(data);
    } catch (error) {
      console.error("获取目录树失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const refreshTree = () => {
    fetchCollectionTree();
  };

  const toggleNode = (id: number, e: React.MouseEvent) => {
    e.stopPropagation();
    const newExpandedNodes = new Set(expandedNodes);
    if (newExpandedNodes.has(id)) {
      newExpandedNodes.delete(id);
    } else {
      newExpandedNodes.add(id);
    }
    setExpandedNodes(newExpandedNodes);
  };

  const handleSelectDirectory = (id: number | null) => {
    onSelectDirectory(id === null ? null : id.toString());
  };

  const renderTreeNode = (node: CollectionTreeItem, level: number = 0) => {
    const hasChildren = node.children && node.children.length > 0;
    const isExpanded = expandedNodes.has(node.id);
    const isActive = currentDirectoryId === node.id.toString();

    return (
      <div key={node.id} className="tree-node">
        <div
          className={`
            flex items-center py-1.5 px-2 cursor-pointer
            ${isActive ? 'bg-primary-100 dark:bg-primary-800/30 text-primary' : 'hover:bg-default-100 dark:hover:bg-default-700/30'}
            transition-colors duration-150
          `}
          style={{ paddingLeft: `${(level * 12) + 8}px` }}
          onClick={() => handleSelectDirectory(node.id)}
        >
          {hasChildren && (
            <Button
              isIconOnly
              size="sm"
              variant="light"
              className="min-w-0 w-5 h-5 p-0 mr-1"
              onClick={(e) => toggleNode(node.id, e)}
            >
              {isExpanded ? <BiChevronDown size={16} /> : <BiChevronRight size={16} />}
            </Button>
          )}
          {!hasChildren && <div className="w-5 mr-1"></div>}

          <div className="flex-shrink-0 w-5 h-5 mr-2 flex items-center justify-center">
            {node.icon ? (
              <Image
                src={node.icon}
                alt={node.name}
                className="w-5 h-5 object-cover rounded-sm"
              />
            ) : (
              <span className="text-sm">{node.emoji || "📁"}</span>
            )}
          </div>

          <span className="text-sm truncate" title={node.name}>{node.name}</span>
        </div>

        {hasChildren && isExpanded && (
          <div>
            {node.children.map((child) => renderTreeNode(child, level + 1))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="w-full h-full flex flex-col bg-white dark:bg-default-100 dark:text-white">
      <div className="border-b border-divider py-2 px-3 flex justify-between items-center">
        <h3 className="text-md font-medium">目录导航</h3>
        <div className="flex items-center">
          <Button
            isIconOnly
            size="sm"
            variant="light"
            onClick={refreshTree}
            className="min-w-0 p-0 mr-1"
            title="刷新目录树"
          >
            <BiRefresh size={16} />
          </Button>
          {onToggleVisibility && (
            <Button
              isIconOnly
              size="sm"
              variant="light"
              onClick={onToggleVisibility}
              className="min-w-0 p-0"
            >
              <BiChevronLeft size={18} />
            </Button>
          )}
        </div>
      </div>
      <div className="flex-1 overflow-auto p-1">
        {loading ? (
          <div className="flex justify-center items-center py-4">
            <Spinner size="sm" color="primary" label="加载中..." />
          </div>
        ) : (
          <div className="directory-tree">
            <div
              className={`
                flex items-center py-1.5 px-2 cursor-pointer mb-1 
                ${currentDirectoryId === null ? 'bg-primary-100/50 dark:bg-primary-800/30 text-primary' : 'hover:bg-default-100 dark:hover:bg-default-700/30'}
                transition-colors duration-150
              `}
              onClick={() => handleSelectDirectory(null)}
            >
              <div className="flex-shrink-0 w-5 h-5 mr-2 flex items-center justify-center">
                <BiHomeAlt size={16} />
              </div>
              <span className="text-sm">根目录</span>
            </div>

            {collections.map((collection) => renderTreeNode(collection))}
          </div>
        )}
      </div>
    </div>
  );
} 